import { ctx } from '../entrance/inter';
import color from '../kernel/tools/color';
import RequestModel from './ctx/RequestModel';
import ResponseModel from './ctx/ResponseModel';
import { IncomingMessage, ServerResponse } from 'http';
import Request from "../interface/Request"
import Response from "../interface/Response"

/**
 * ctx的模型，存储了ctx的类型和方法
 */
 
export default class CtxModel implements ctx {
    // req,res 是原生的
    public req:IncomingMessage = null;
    public res:ServerResponse = null;
    // $req,$res 是保留的
    public $req:IncomingMessage = null;
    public $res:ServerResponse = null;
    // 框架封装的
    public request:Request = null;
    public response:Response = null;

    public cookie:Function = CtxModel.agent(this,"request","cookie");
    public startAsync: any = CtxModel.agent(this,"response","startAsync");
    public body: any = CtxModel.agent(this,"response","body");
    public proxy: any = CtxModel.agent( this,"response","proxy");
    public sendFile: any = CtxModel.agent(this,"response","sendFile");
    public redirect: any = CtxModel.agent(this,"response","redirect");
    public echo: any =  CtxModel.agent(this,"response","echo");
    public $all: any = CtxModel.agent(this,"response","startAsync");
    /**
     * 构造方法
     */
    constructor(req:IncomingMessage,res:ServerResponse){
        this.req = this.$req = req;
        this.res = this.$res = res;
        this.request = new RequestModel(this);
        this.response = new ResponseModel(this);

        res.on("end",()=>{this.response.isClose = true;})
        res.on("error",(err)=>{
            if(err.message === "write after end"){
                console.log(color("红色","写入流已关闭，如需进行异步返回，请先开启异步 ctx.startAsync()\n\n"))
            }else{
                console.log(err)
            }
        })
    }


    /**
     * 代理一下类方法
     */
    static agent(fun:any,methodName:string,methodName2:string){
        return function (...a){
            return fun[methodName][methodName2](...a);
        }
    }
}